#include "InputMouse.h"
#include "Visualisation.h"
#include "UserInterface.h"
#include "WorldModel.h"

CInputMouse::CInputMouse(void):m_diMouseDevice(0)
{
}

CInputMouse::~CInputMouse(void)
{
	if(m_diMouseDevice)
	{
		m_diMouseDevice->Unacquire();
		m_diMouseDevice->Release();
	}
}

bool CInputMouse::initialise(const LPDIRECTINPUT8 diObject)
{
	//create the device object that represent the mouse
	HRESULT hr = diObject->CreateDevice(GUID_SysMouse, &m_diMouseDevice, NULL);
	if(FAILED(hr))
		return false;

	//set the data format
	hr=m_diMouseDevice->SetDataFormat(&c_dfDIMouse2);
	if(FAILED(hr))
		return false;

	//set the behaviour
	hr=m_diMouseDevice->SetCooperativeLevel(VIS->getWindowHandle(), DISCL_FOREGROUND | DISCL_NONEXCLUSIVE);
	if(FAILED(hr))
		return false;

	//acquire mouse device
	hr=m_diMouseDevice->Acquire();
	while( hr == DIERR_INPUTLOST )
    {     
       hr = m_diMouseDevice->Acquire();
    }
	return true;
}

bool CInputMouse::initialiseActionMapping(Element root)
{
	list<Element> keyboard=root.Children();
	//for each line
	for(list<Element>::iterator i=keyboard.begin(); i!=keyboard.end(); i++)
	{
		int indexAction=getIndexAction(i->Name());
		if(indexAction==-1)
			return false;

		std::string key=i->Content();
		m_actionMapArray[indexAction]=UI->getDirectInputValue(key);
	}
	return true;
}

void CInputMouse::doUpdate(void)
{
	//get the mouse input
	ZeroMemory( &m_mouseState, sizeof(m_mouseState) );
	HRESULT hr = m_diMouseDevice->GetDeviceState( sizeof(DIMOUSESTATE2), &m_mouseState );
	if (FAILED(hr))
	{
		// acquire the device till success
		HRESULT hr=m_diMouseDevice->Acquire();
		while( hr == DIERR_INPUTLOST )
		{     
		   hr = m_diMouseDevice->Acquire();
		}

		if (FAILED(hr))
			 return;
		//get the inputs
		hr=m_diMouseDevice->GetDeviceState( sizeof(DIMOUSESTATE2), &m_mouseState );	
	}

	if(m_mouseState.rgbButtons[m_actionMapArray[eTurnLeftRight]]&0x80)
	{
		WORLDMODEL->turnPlayerLeftRight((float)m_mouseState.lX);
	}
	if(m_mouseState.rgbButtons[m_actionMapArray[eLookUpDown]]&0x80)
	{
		WORLDMODEL->playerLookUpDown((float)m_mouseState.lY);
	}
}
